/**
 The MIT License

Copyright (c) <2011> <JPACHUBE Team>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
package com.pachube.v2.impl;

import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.pachube.api.Domain;
import com.pachube.api.Exposure;
import com.pachube.api.Feed;
import com.pachube.api.Location;
import com.pachube.api.Status;
import com.pachube.api.Trigger;
import com.pachube.api.TriggerType;
import com.pachube.commons.impl.DataImpl;
import com.pachube.commons.impl.FeedImpl;
import com.pachube.commons.impl.LocationImpl;
import com.pachube.commons.impl.TriggerImpl;
import com.pachube.exceptions.PachubeException;

/**
 * The Class PachubeV2Utils.
 */
public class PachubeV2Utils {

    /**
     * Creates a feed from a String.
     * 
     * @param p Pachube2 object which is the gateway to the pachube service
     * @param s String which represents a feed object, this String should be
     *            well formed eeml.
     * @return Feed manufactured from the String
     */
    public static Feed toFeed(PachubeV2Impl p, String s) {
        Feed f = new FeedImpl(p);

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new ByteArrayInputStream(s
                    .getBytes("UTF-8")));
            doc.getDocumentElement().normalize();
            PachubeV2Utils.getMisc(f, doc);
            PachubeV2Utils.getData(f, doc);
            PachubeV2Utils.getlocation(f, doc);

        } catch (Exception e) {
            e.printStackTrace();
        }
        f.setCreated(true);
        return f;
    }

    /**
     * Method to retrieve data from eeml.
     * 
     * @param f the f
     * @param doc the doc
     * @return the misc
     * @throws DOMException the dOM exception
     * @throws PachubeException the pachube exception
     */
    private static void getMisc(Feed f, Document doc) throws DOMException,
            PachubeException {
        NodeList nodeLst = doc.getElementsByTagName("environment");
        Node c = nodeLst.item(0);

        NamedNodeMap n = c.getAttributes();
        Node h = n.getNamedItem("updated");
        if (h != null) {
            f.setUpdated(h.getNodeValue());
        }
        f.setId((n.getNamedItem("id").getNodeValue()));
        if (c.getNodeType() == Node.ELEMENT_NODE) {

            Element e = (Element) c;

            NodeList fstNmElmntLst = e.getElementsByTagName("title");
            Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
            NodeList fstNm = fstNmElmnt.getChildNodes();
            f.setTitle((fstNm.item(0)).getNodeValue());

            fstNmElmntLst = e.getElementsByTagName("status");
            fstNmElmnt = (Element) fstNmElmntLst.item(0);
            fstNm = fstNmElmnt.getChildNodes();
            f.setStatus(Status.valueOf((fstNm.item(0)).getNodeValue()));

            fstNmElmntLst = e.getElementsByTagName("description");
            fstNmElmnt = (Element) fstNmElmntLst.item(0);

            if (fstNmElmnt != null) {
                fstNm = fstNmElmnt.getChildNodes();
                h = (fstNm.item(0));
                f.setDescription(h.getNodeValue());
            }

            fstNmElmntLst = e.getElementsByTagName("website");
            fstNmElmnt = (Element) fstNmElmntLst.item(0);

            if (fstNmElmnt != null) {
                fstNm = fstNmElmnt.getChildNodes();
                try {
                    f.setWebsite(new URL((fstNm.item(0)).getNodeValue()));
                } catch (Exception e3) {

                }
            }

            fstNmElmntLst = e.getElementsByTagName("feed");
            fstNmElmnt = (Element) fstNmElmntLst.item(0);
            fstNm = fstNmElmnt.getChildNodes();
            try {
                f.setFeed(new URL((fstNm.item(0)).getNodeValue()));
            } catch (Exception e3) {

            }

        }

    }

    /**
     * Method to retrieve data from eeml.
     * 
     * @param f the f
     * @param doc the doc
     * @return the location
     * @throws PachubeException the pachube exception
     */
    private static void getlocation(Feed f, Document doc)
            throws PachubeException {
        NodeList nodeLst = doc.getElementsByTagName("location");
        Node c = nodeLst.item(0);
        Location l = new LocationImpl();
        NamedNodeMap n;
        if (c != null) {
            n = c.getAttributes();
            l.setDomain(Domain.valueOf(n.getNamedItem("domain").getNodeValue()));

            Node h = n.getNamedItem("exposure");

            if (h != null) {
                l.setExposure(Exposure.valueOf(h.getNodeValue()));
            }

            h = n.getNamedItem("disposition");
            if (h != null) {
                l.setExposure(Exposure.valueOf(h.getNodeValue()));
            }

            if (c.getNodeType() == Node.ELEMENT_NODE) {

                Element e = (Element) c;

                NodeList fstNmElmntLst = e.getElementsByTagName("name");
                Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                NodeList fstNm;
                if (fstNmElmnt != null) {
                    fstNm = fstNmElmnt.getChildNodes();
                    l.setName((fstNm.item(0)).getNodeValue());
                }

                fstNmElmntLst = e.getElementsByTagName("lat");
                fstNmElmnt = (Element) fstNmElmntLst.item(0);
                fstNm = fstNmElmnt.getChildNodes();
                h = (fstNm.item(0));
                if (h != null) {
                    l.setLat(h.getNodeValue());
                }

                fstNmElmntLst = e.getElementsByTagName("lon");
                fstNmElmnt = (Element) fstNmElmntLst.item(0);
                fstNm = fstNmElmnt.getChildNodes();

                h = (fstNm.item(0));
                if (h != null) {
                    l.setLon(h.getNodeValue());
                }

                fstNmElmntLst = e.getElementsByTagName("ele");
                fstNmElmnt = (Element) fstNmElmntLst.item(0);

                if (fstNmElmnt != null) {
                    fstNm = fstNmElmnt.getChildNodes();
                    h = (fstNm.item(0));
                    if (h != null) {
                        l.setElevation(h.getNodeValue());
                    }
                }
            }

        }
        // System.out.println(l.toString());
        f.setLocation(l);

    }

    /**
     * Method to retrieve data from eeml.
     * 
     * @param f the f
     * @param doc the doc
     * @return the data
     */
    private static void getData(Feed f, Document doc) {
        NodeList nodeLst = doc.getElementsByTagName("data");
        DataImpl d;
        for (int i = 0; i < nodeLst.getLength(); i++) {
            d = new DataImpl();
            Node fstNode = nodeLst.item(i);

            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

                Element fstElmnt = (Element) fstNode;

                NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("tag");
                Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                if (fstNmElmnt != null) {
                    NodeList fstNm = fstNmElmnt.getChildNodes();
                    d.setTag((fstNm.item(0)).getNodeValue());
                }
                d.setId(fstNode.getAttributes().getNamedItem("id")
                        .getNodeValue());
                NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("value");
                Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                NodeList lstNm = lstNmElmnt.getChildNodes();
                Node h = (lstNm.item(0));
                if (h != null) {
                    d.setValue(h.getNodeValue());
                }

                h = lstNmElmnt.getAttributes().getNamedItem("minValue");
                if (h != null) {
                    d.setMinValue(h.getNodeValue());
                }

                h = lstNmElmnt.getAttributes().getNamedItem("maxValue");
                if (h != null) {
                    d.setMaxValue(h.getNodeValue());
                }

                f.addData(d);
            }

        }
    }

    /**
     * Creates a Trigger from a String.
     * 
     * @param s String which represents a trigger object, this String should be
     *            well formed eeml.
     * @return Trigger array manufactured from the String
     */
    public static Trigger[] toTrigger(String s) {
        ArrayList<TriggerImpl> tL = new ArrayList<TriggerImpl>();

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new ByteArrayInputStream(s
                    .getBytes("UTF-8")));
            doc.getDocumentElement().normalize();

            /*****************************************************
			 * 
			 */

            NodeList nodeLst = doc.getElementsByTagName("datastream-trigger");

            for (int i = 0; i < nodeLst.getLength(); i++) {
                TriggerImpl t = new TriggerImpl();
                Node c = nodeLst.item(i);

                if (c != null) {

                    if (c.getNodeType() == Node.ELEMENT_NODE) {

                        Element e = (Element) c;

                        NodeList fstNmElmntLst = e.getElementsByTagName("id");
                        Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        NodeList fstNm;
                        if (fstNmElmnt != null) {
                            fstNm = fstNmElmnt.getChildNodes();
                            t.setID(Integer.parseInt(((fstNm.item(0))
                                    .getNodeValue())));
                        }

                        fstNmElmntLst = e.getElementsByTagName("url");
                        fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        fstNm = fstNmElmnt.getChildNodes();
                        Node h = (fstNm.item(0));
                        if (h != null) {
                            try {
                                t.setUrl(new URL(h.getNodeValue()));
                            } catch (MalformedURLException err) {
                                t.setUrl(null);
                            }
                        }

                        fstNmElmntLst = e.getElementsByTagName("trigger-type");
                        fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        fstNm = fstNmElmnt.getChildNodes();

                        h = (fstNm.item(0));
                        if (h != null) {
                            t.setType(TriggerType.valueOf(h.getNodeValue()));
                        }

                        fstNmElmntLst = e
                                .getElementsByTagName("threshold-value");
                        fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        fstNm = fstNmElmnt.getChildNodes();

                        h = (fstNm.item(0));
                        if (h != null) {
                            t.setThreshold(Double.parseDouble(h.getNodeValue()));
                        }

                        fstNmElmntLst = e
                                .getElementsByTagName("environment-id");
                        fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        fstNm = fstNmElmnt.getChildNodes();

                        h = (fstNm.item(0));
                        if (h != null) {
                            t.setEnv_id(Integer.parseInt(h.getNodeValue()));
                        }

                        fstNmElmntLst = e.getElementsByTagName("stream-id");
                        fstNmElmnt = (Element) fstNmElmntLst.item(0);
                        fstNm = fstNmElmnt.getChildNodes();

                        h = (fstNm.item(0));
                        if (h != null) {
                            t.setStream_id(Integer.parseInt(h.getNodeValue()));
                        }
                    }

                }

                tL.add(t);
            }

            /******************************************************************
			 * 
			 */

        } catch (Exception e) {
            e.printStackTrace();
        }

        return tL.toArray(new TriggerImpl[0]);
    }

}
